package com.cn.qgx428.lazydiary.ui.timeline

import android.content.Context
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.Presenter.DiaryPresenter
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.Utils.SPUtil
import com.cn.qgx428.lazydiary.network.Imageloader
import com.cn.qgx428.lazydiary.network.bean.Diary
import com.cn.qgx428.lazydiary.ui.activity.HomeActivity
import com.cn.qgx428.lazydiary.ui.activity.subActivity.DiaryEditActivity
import de.hdodenhof.circleimageview.CircleImageView
import org.jetbrains.anko.startActivity

/**
 * Created by qinguanxiong on 2018/4/7.
 */
class T_Diary(context: Context, mView: View?) : T_Base(context, mView) {

    lateinit var title_txt: TextView
    lateinit var content_txt: TextView
    lateinit var mImg: CircleImageView
    lateinit var time_txt: TextView
    lateinit var mainLayout: LinearLayout
    var mDiary: Diary? = null

    override fun initView() {
        time_txt = getView(R.id.timeline_diary_time)
        content_txt = getView(R.id.timeline_diary_content)
        mImg = getView(R.id.timeline_diary_img)
        title_txt = getView(R.id.timeline_diary_title)
        mainLayout = getView(R.id.timeline_diary_layout)
        mainLayout.setOnClickListener { mContext.startActivity<DiaryEditActivity>(
                MConst.DIARY_TYPE to MConst.DIARY_EDIT,
                MConst.DIARY_BUNDLE to mDiary
        ) }
    }

    override fun initEvent() {
    }

    override fun getData() {
        if ((mContext as HomeActivity).checkLoginAndNetWork()){
            DiaryPresenter.getLatestBrife(SPUtil.currntUserId().toInt(), {
                res ->
                if (res.diary!=null){
                    mDiary = res.diary
                    mainLayout.visibility = View.VISIBLE
                    time_txt.text = res.diary.createtime
                    title_txt.text = res.diary.title
                    val contents = res.diaryContents
                    if (contents!=null){
                        if (contents.size >0){
                            var content = contents[0].info
                            if (content.length > 30)
                                content = content.substring(0..30) + "..."
                            content_txt.text = content
                        }
                        if(contents.size >1){
                            Imageloader.download(mContext, mImg, contents[1].info)
                            mImg.visibility = View.VISIBLE
                        } else{
                            mImg.visibility = View.GONE
                        }
                    }
                }
            })
        } else{
            mainLayout.visibility = View.GONE
        }
    }

    override fun onDataChange() {
        getData()
    }
}